/**
 * @Description:
 * @author longfa liang
 * @date 2021/7/13
 */

/**
 * 1、创建流程
 * 2、发起人节点自动审核通过
 * 3、审核通过后 检测下个节点 如果是通知节点 直接通过并且通过邮件或者消息通知
 * 4、用户审核操作后根据线条条件设置下个环节审核人 审核节点id 并且审核后做记录
 * 5、审核完过后删除当前表在另外表做归档
 */


var pu = require('../tool/public')
var mg = require('../db/userdb')
var pr_mg = require('../db/processdb')
var process_approve = require('../process/approve')
var jurupdate = require('../tool/jurUpdate')
var message = require('../tool/message')

class process {


    /*查询流程审核记录*/
    async find_agency (req, res, next) {
        let userid = req.headers.uid
        let team_id = req.headers.team
        let template_uuid = req.body.template_uuid //表单ID
        let department_id = req.body.department_id //部门ID
        let _id = req.body._id //部门ID
        let startdate = req.body.startdate //开始日期
        let stoptdate = req.body.stoptdate //结束日期
        let start_launchdate = req.body.start_launchdate //结束发起日期
        let stop_launchdate = req.body.stop_launchdate //结束发起日期
        let start_user = req.body.start_user //发起人
        let status = Number(req.body.status) //
        let serial_number = req.body.serial_number //
        let type = Number(req.body.type) // 记录类型  1 我发起的  2 抄送我的 3 我审核过的
        let find_type = Number(req.body.find_type)  //0查询待审批 1查询归档的 2查询操作记录
        var pageSize = req.body.pageSize
        var last_page_id = req.body.last_page_id

        var where = {
            team_id: mg.ObjectID(team_id),
            user: { $elemMatch: { userid: mg.ObjectID(userid) } }
        }

        if (_id) { //查询记录时如果需要查询具体内容需要到两张表里面查询
            let info = await pr_mg.findOne('process_file', { process_id: mg.ObjectID(_id) })
            let info2 = await pr_mg.findOne('process', { _id: mg.ObjectID(_id) })
            pu.success('OK', [info, info2], res)
            return
        }

        if (department_id) {
            where.department_id = mg.ObjectID(department_id)
        }

        if (start_launchdate || stop_launchdate) {
            where.startTime = {}
        }
        if (start_launchdate) {

            where.startTime['$gte'] = start_launchdate
        }
        if (stop_launchdate) {
            where.startTime['$lte'] = stop_launchdate
        }

        if (stoptdate || stoptdate) {
            where.date = {}
        }

        if (startdate) {
            where.date['$gte'] = startdate
        }

        if (stoptdate) {
            where.date['$lte'] = stoptdate
        }

        if (start_user) {
            delete where.user
            where.startUserid = mg.ObjectID(start_user)
        }

        if (status || status == 0) {
            where.status = status
        }

        if (type || type == 0) {
            where.type = type
        }
        if (serial_number) {
            where.serial_number = { $regex: serial_number }
        }

        if (pageSize && isNaN(pageSize)) {
            pu.fail('页数不正确', res)
            return
        }

        var tables = 'process'


        if (find_type == 0) { //正在跑的流程
            tables = 'process' //审核过的
        }

        if (find_type == 1) { //归档的
            tables = 'process_file'
        }

        if (find_type == 2) { //查询记录
            tables = 'process_record' //我自己操作记录
            where.userid = mg.ObjectID(userid)
            delete where.user
        }
        console.log(where)

        if (pageSize && !last_page_id) { //查询第一页
            let userinfo = await pr_mg.find(tables, where, {}, 0, Number(pageSize), {}, true)
            for (var i = 0; i < userinfo[0].length; i++) {
                if (!userinfo[0][i].view_records) {
                    delete userinfo[0][i].record
                }
            }
            var resdata = {
                data: userinfo[0],
                allsum: userinfo[1]
            }
            pu.success('OK', resdata, res)
            return
        } else {
            var resdata = []
            if (last_page_id) {
                resdata = await pr_mg.find(tables, where, {}, 0, Number(pageSize))
            } else {
                console.log(tables, where)
                resdata = await pr_mg.find(tables, where)
            }

            for (var i = 0; i < resdata.length; i++) {
                if (!resdata.view_records) {
                    delete resdata.record
                }
            }
            pu.success('OK', resdata, res)
            return
        }

    }

    /*编辑流程 */
    async update_process (req, res, next) {
        let uuid = req.body.uuid
        let userid = req.headers.uid //
        let modeule = req.headers.modeule //
        let team_id = req.headers.team //
        let release = req.body.release || 0//状态 0保存 1发布
        let node = req.body.node  //审核节点
        let lin = req.body.lin   //审核流程
        let isnull = pu.isnull([release, uuid])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let data = await pr_mg.find('process_module', { team_id: pr_mg.ObjectID(team_id), uuid: uuid }, '', '', 1, { version: -1 })
        if (!data.length) {
            pu.fail('_id不正确', res)
            return
        } else {
            data = data[0]
            console.log(data)
            data.userid = pr_mg.ObjectID(userid)
            if (node) {
                data.node = node
            }
            if (lin) {
                data.lin = lin
            }
            data.release = release

            if (data.release == 0 && release == 0) { //保存状态中 并且在保存
                await pr_mg.updateOne('process_module', { _id: data._id }, { $set: data })
            } else {
                delete data._id
                if (release === 1 && data.version == 1) {//发布
                    var newteam = {
                        name: name,
                        server: 'template',
                        status: 1,
                        url: uuid,
                        type: 'custom',
                        adopt: ['*'],
                        field: ['*'],
                        jurlist: []
                    }
                    jurupdate.jurupdate(team_id, newteam, modeule,1) //修改公司权限
                }


                data.version = data.version + 1
                await pr_mg.insertOne('process_module', data)


            }
            pu.success('OK', data, res)
            return
        }
    }

    /*查询流程 */
    async find_process (req, res, next) {
        let team_id = req.headers.team
        let _id = req.body._id
        let uuid = req.body.uuid
        let sort = req.body.sort
        let release = req.body.release || 0//状态 0保存 1发布
        let text = req.body.text //模糊查询
        let isnull = pu.isnull([team_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        if (_id) {
            let info = await pr_mg.findOne('process_module', { _id: mg.ObjectID(_id) })
            pu.success('OK', info, res)
            return
        }
        let where = {
            team_id: mg.ObjectID(team_id)
        }

        if (uuid) {
            where.uuid = uuid
        }
        if (release) {
            where.release = release
        }
        var limit = ''
        if (sort) {
            limit = 1
        }
        if (text) {
            where.text = { $regex: text }
        }
        let info = await pr_mg.find('process_module', where, '', '', limit, { version: -1 })
        pu.success('OK', info, res)
    }

    /*新增流程 */
    async add_process (req, res, next) {

        console.log(JSON.stringify(req.body))
        let team_id = req.headers.team
        let node = req.body.node  //审核节点
        let lin = req.body.lin   //审核流程
        let userid = req.headers.uid //新增用户id
        let name = req.body.name  // 表单名称
        let explain = req.body.explain//备注
        let modeule = req.body.modeule
        let template_id = req.body.template_id//模板id
        let template_uuid = req.body.template_uuid//模板uuid
        let template_name = req.body.template_name //模板名称
        let view_records = req.body.view_records //是否允许查看记录
        let withdraw = req.body.withdraw //是否允许撤回
        let release = Number(req.body.release) || 0//状态 0保存 1发布

        let isnull = pu.isnull([node, lin, name, modeule, template_id, template_name])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let info = await mg.findOne('template', { _id: mg.ObjectID(template_id) })
        if (info) {
            pu.fail('该表单已有流程:' + info.name, res)
            return
        }
        var is_start = false
        var is_stop = false
        for (var i = 0; i < node.length; i++) {

            if (!node[i].id || !node[i].is_all_agree || !node[i].is_all_agree || !node[i].is_all_agree || !node[i].is_all_agree || !node[i].is_all_agree) {
            }
            if (node[i].type == 'start') {
                if (is_start == true) {
                    is_start = false
                } else {
                    is_start = true
                }
            }
            if (node[i].type == 'stop') {
                if (is_stop == true) {
                    is_stop = false
                } else {
                    is_stop = true
                }
            }
        }
        if (!is_start || !is_stop) {
            pu.fail('开始节点或者结束节点不正确', res)
            return
        }
        var uuid = pu.uuid()
        var inserdata = {
            team_id: mg.ObjectID(team_id),
            node: node
            , lin: lin,
            userid: mg.ObjectID(userid),
            version: 1,
            is_delete: 0,
            name: name,
            time: new Date().getTime(),
            explain: explain,
            template_id: mg.ObjectID(template_id),
            template_name: template_name,
            release: release,
            view_records: view_records,
            withdraw: withdraw,
            uuid: uuid,
            template_uuid: template_uuid
        }
        var inser = await pr_mg.insertOne('process_module', inserdata)
        if (inser.insertedId) {
            inserdata._id = inser.insertedId
            await pr_mg.updateOne('template', { _id: mg.ObjectID(template_id) }, { $set: { processuuid: uuid } })


            console.log('发布时候状态', release, inserdata.version)
            if (release === 1 && inserdata.version == 1) {//发布

                var newteam = {
                    name: template_name,
                    server: 'template',
                    status: 0,
                    url: uuid,
                    _id: inser.insertedId,
                    type: 'custom',
                    adopt: ['*'],
                    field: ['*'],
                    jurlist: []
                }
                jurupdate.jurupdate(team_id, newteam, modeule,0) //修改公司权限
                pu.success('OK', inserdata, res)
            } else {
                pu.success('OK', inserdata, res)
            }
        } else {
            pu.fail('数据格式不正确', res)
            return
        }
    }


    /*审核流程*/
    async audit_process (req, res, next) {
        let process_id = req.body.process_id  //流程id
        let userid = req.headers.uid //发起人ID
        let status = Number(req.body.status)  //审核状态
        let describe = req.body.describe  //备注
        let username = req.body.username //发起人名字
        let nodeid = req.body.nodeid //处理节点
        let reject_id = req.body.reject_id //驳回节点id


        let isnull = pu.isnull([userid, process_id, status])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let process = await pr_mg.findOne('process', { _id: pr_mg.ObjectID(process_id) })

        if (!process) {
            pu.fail('id不正确', res)
            return
        }
        if (process.status == 4) {
            pu.fail('流程已经作废', res)
            return
        }

        if (status == 1) { //通过
            if (!username || !nodeid) {
                pu.fail('参数不正确', res)
                return
            }
            pu.success('OK', '', res)
            /*流程审核钩子*/                //process_id, template, user, status, describe, nodeid, reject_id
            process_approve.approve_succesc(pr_mg.ObjectID(process_id), process.template, [{ userid: userid, username: username }], status, describe, nodeid)

        }

        if (status == 2) { //驳回
            pu.success('OK', '', res)
            /*流程审核钩子*/
            if (!reject_id) {
                pu.fail('请选择驳回节点', res)
                return
            }
            process_approve.approve_succesc(pr_mg.ObjectID(process_id), process.template, [{
                userid: userid,
                username: username
            }], status, describe, nodeid, reject_id)

        }

        if (status == 3) { //发起人撤回
            pu.success('OK', '', res)
            /*流程审核钩子*/
            if (!reject_id) {
                pu.fail('请选择撤回节点', res)
                return
            }
            process_approve.approve_succesc(pr_mg.ObjectID(process_id), process.template, [{
                userid: userid,
                username: username
            }], status, describe, nodeid, reject_id)

        }
        if (status == 4) { //作废
            pu.success('OK', '', res)
            /*流程审核钩子*/
            process_approve.approve_succesc(pr_mg.ObjectID(process_id), process.template, [{
                userid: userid,
                username: username
            }], status, describe, nodeid, reject_id)

        }


        // async approve_succesc(process_id, template, user, status, describe, nodeid, reject_id) {

    }

    /*发起流程*/
    async launch_process (req, res, next) {
        let userid = req.headers.uid //发起人ID
        let team_id = req.headers.team //发起人ID

        let username = req.body.username //发起人名字
        let template_id = req.body.template_id //模板ID

        let department_id = req.body.department_id //部门ID
        let department = req.body.department //部门


        let template = req.body.template //模板信息
        let uuid = req.body.uuid //模板信息
        let isnull = pu.isnull([userid, template_id, uuid, template])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        console.log({ team_id: mg.ObjectID(team_id), uuid: uuid, is_delete: 0 })
        /*创建流程*/
        let templateinfo = await pr_mg.find('template', { team_id: mg.ObjectID(team_id), uuid: uuid, is_delete: 0 }, {}, '', 1, { version: -1 })
        if (!templateinfo.length) {
            pu.fail('UUID 不正确', res)
            return
        }
        templateinfo = templateinfo[0]
        let process = await pr_mg.find('process_module', {
            team_id: mg.ObjectID(team_id),
            uuid: templateinfo.processuuid,
            is_delete: 0
        }, {}, '', 1, { version: -1 })

        if (!process.length) {
            pu.fail('该表单还没有流程', res)
            return
        }
        process = process[0]
        /*发起流程后自动审核通过*/
        var nodeid = ''
        let insertdata = {
            template_name: templateinfo.name,
            template_uuid: uuid,
            process_name: process.name,
            process_uuid: process.uuid,
            startTime: new Date().getTime(),//发起时间
            template_id: pr_mg.ObjectID(template_id),
            template: template,
            team_id: pr_mg.ObjectID(team_id),
            template_version: templateinfo.version, //模板版本
            process_version: process.version,//流程版本
            node: process.node, //所有节点
            lin: process.lin, //所有线
            current_nodeid: '',//当前节点ID
            department_id: !department_id ? '' : pr_mg.ObjectID(department_id),//部门ID
            department: department,//部门
            user: [ //当前处理人就是流程所在的位置
                { userid: pr_mg.ObjectID(userid), name: username }
            ],

            date: +new Date(),
            readyuserid: [],//当前节点处理的人
            record: [],//处理记录
            serial_number: pu.randomWord(15, 15).toLocaleUpperCase(),
            startUserid: pr_mg.ObjectID(userid), //发起人id
            startUserName: username, //发起人名字
            status: 0//处理状态  0审核中  1审核完成 2驳回 3撤回 4 作废,
        }
        let info = await pr_mg.insertOne('process', insertdata)
        insertdata._id = info.insertedId
        pu.success('OK', insertdata, res)
        for (var i = 0; i < insertdata.node.length; i++) {
            if (insertdata.node[i].type == 'start') {
                nodeid = insertdata.node[i].id
            }
        }
        process_approve.approve_succesc(insertdata._id, template, [{ userid: userid, username: username }], 1, '发起流程', nodeid)
    }
}


module.exports = new process()
